define(function (require) {
    "use strict";
    var ko = require("knockout");
    var komapping = require("komapping");
    var router = require("plugins/router");
    var layui = require("layui");
    var $ = require("jquery");
    var system = require("durandal/system");
    var singleReviewTemp = require("text!./single-review-temp.html");
    var shareUrlContent = require("text!../trace/share-url-content.html");
    var ParamCommon = require("../param/ParamCommon");

    var acceptPageSize = [10, 30, 60, 90, 150, 300];
    var param = {
        searchDate: ko.observable(""),
        actionId: ko.observable(""),
        codeArrayInclude: ko.observable(""),
        codeArrayExclude: ko.observable(""),
        hostInclude: ko.observable(""),
        hostExclude: ko.observable(""),
        refererInclude: ko.observable(""),
        refererExclude: ko.observable(""),
        protocolInclude: ko.observable(""),
        protocolExclude: ko.observable(""),
        urlInclude: ko.observable(""),
        urlExclude: ko.observable(""),
        typeInclude: ko.observable(""),
        typeExclude: ko.observable(""),
        minSize: ko.observable("-1"),
        curr: 1,
        limit: acceptPageSize[0]
    };

    var currentAction = ko.observable(null);

    var tableModel = {
        id: "account-list",
        elem: "#list-table", //指定原始表格元素选择器（推荐id选择器）
        height: "full-227", //容器高度
        cols: [[
            //标题栏
            {title: "操作", width: 66, templet: singleReviewTemp},
            {field: "status", title: "状态码", width: 80},
            {
                title: "请求耗时", width: 94, templet: function (d) {
                    return d.wasteTime + "ms";
                }
            },
            {field: "url", title: "目标链接", width: 500},
            {field: "host", title: "主机头", width: 200},
            {field: "protocol", title: "协议", width: 80},
            {field: "contentType", title: "ContentType", width: 180},
            {
                title: "大小", width: 120, templet: function (d) {
                    if (d.contentLength !== null) {
                        if (d.contentLength < 1024 * 1024) {
                            var num = d.contentLength / 1024;
                            return parseInt(num * 1000) / 1000 + "KB";
                        } else {
                            var num = d.contentLength / 1024 / 1024;
                            return parseInt(num * 1000) / 1000 + "MB";
                        }
                    } else {
                        return "未知";
                    }
                }
            },
            {field: "deep", title: "深度", width: 80},
            {
                title: "请求时间", width: 280, templet: function (d) {
                    return new Date(d.requestTime).toString();
                }
            }
        ]], //设置表头
        url: "/back/planUrls",
        page: {
            limits: acceptPageSize
        },
        done: function (res, curr, count) {
            //设置当前页码
            param.curr = curr;
            //设置当前分页大小
            param.limit = tableIns.config.limit;
        },
        response: {
            statusCode: 200
        }
    };
    /*var searchUrlGen = function(prefix) {
        return prefix + "?" +
            "searchDate=" + encodeURIComponent(param.searchDate()) +
            "&actionId=" + encodeURIComponent(currentAction() ? currentAction().id : "") +
            "&codeArrayInclude=" + encodeURIComponent(param.codeArrayInclude()) +
            "&codeArrayExclude=" + encodeURIComponent(param.codeArrayExclude()) +
            "&hostInclude=" + encodeURIComponent(param.hostInclude()) +
            "&hostExclude=" + encodeURIComponent(param.hostExclude()) +
            "&refererInclude=" + encodeURIComponent(param.refererInclude()) +
            "&refererExclude=" + encodeURIComponent(param.refererExclude()) +
            "&protocolInclude=" + encodeURIComponent(param.protocolInclude()) +
            "&protocolExclude=" + encodeURIComponent(param.protocolExclude()) +
            "&urlInclude=" + encodeURIComponent(param.urlInclude()) +
            "&urlExclude=" + encodeURIComponent(param.urlExclude()) +
            "&typeInclude=" + encodeURIComponent(param.typeInclude()) +
            "&typeExclude=" + encodeURIComponent(param.typeExclude()) +
            "&minSize=" + encodeURIComponent(param.minSize());
    };*/
    var tableIns = null;

    var modelId = null;

    return {
        activate: function (id, queryParam) {
            modelId = id;
            ParamCommon.setParamFromUrl(param, queryParam);
            /*return $.ajax({
                type: "get",
                url: "/back/actionIdFromTime",
                dataType: "json",
                data: { time: param.searchDate(), planId: modelId }
            }).then(function(response) {
                currentAction(response.data);
            }, function(data) {
                layui.use(["layer"], function() {
                    var layer = layui.layer;
                    layer.alert(data.responseJSON.msg);
                });
            });*/
            var promise = null;
            if (param.actionId()) {
                promise = $.ajax({
                    type: "get",
                    url: "/back/actionById/" + param.actionId(),
                    dataType: "json"
                }).then(function (response) {
                    currentAction(response.data);
                }, function (data) {
                    layui.use(["layer"], function () {
                        var layer = layui.layer;
                        layer.alert(data.responseJSON.msg);
                    });
                });
            } else {
                promise = $.ajax({
                    type: "get",
                    url: "/back/actionByTime",
                    dataType: "json",
                    data: {time: encodeURIComponent(param.searchDate()), planId: modelId}
                }).then(function (response) {
                    if ((typeof response === "object") && (response !== null)) {
                        currentAction(response.data);
                        param.actionId(response.data.id);
                    }
                }, function (data) {
                    layui.use(["layer"], function () {
                        var layer = layui.layer;
                        layer.alert(data.responseJSON.msg);
                    });
                });
            }
            return promise;
        },
        param: param,
        currentAction: currentAction,
        compositionComplete: function () {
            layui.use(["laytpl", "table", "element", "layer", "laydate", "form"], function () {
                var laytpl = layui.laytpl;
                var table = layui.table;
                var element = layui.element;
                var layer = layui.layer;
                var laydate = layui.laydate;
                var form = layui.form;

                tableModel.where = {
                    codeArrayInclude: param.codeArrayInclude(),
                    codeArrayExclude: param.codeArrayExclude(),
                    hostInclude: param.hostInclude(),
                    hostExclude: param.hostExclude(),
                    refererInclude: param.refererInclude(),
                    refererExclude: param.refererExclude(),
                    protocolInclude: param.protocolInclude(),
                    protocolExclude: param.protocolExclude(),
                    urlInclude: param.urlInclude(),
                    urlExclude: param.urlExclude(),
                    typeInclude: param.typeInclude(),
                    typeExclude: param.typeExclude(),
                    minSize: param.minSize(),
                    actionId: currentAction() ? currentAction().id : "",
                    planId: modelId
                };
                tableModel.page.curr = param.curr;
                tableModel.page.limit = param.limit;

                tableIns = table.render(tableModel);

                table.on("tool(list-table)", function (obj) {
                    var data = obj.data;
                    if (obj.event === "anchor") {
                        window.open("/kunlunAssets/index.html#plan/trace/" + modelId + "?searchDate=" + encodeURIComponent(param.searchDate()) + "&term=" + encodeURIComponent(data.url) + "&actionId=" + encodeURIComponent(param.actionId()));
                        return true;
                    }
                });

                form.on("submit(search-submit)", function (data) {
                    var searchObjUpdate = {
                        where: {
                            codeArrayInclude: param.codeArrayInclude(),
                            codeArrayExclude: param.codeArrayExclude(),
                            hostInclude: param.hostInclude(),
                            hostExclude: param.hostExclude(),
                            refererInclude: param.refererInclude(),
                            refererExclude: param.refererExclude(),
                            protocolInclude: param.protocolInclude(),
                            protocolExclude: param.protocolExclude(),
                            urlInclude: param.urlInclude(),
                            urlExclude: param.urlExclude(),
                            typeInclude: param.typeInclude(),
                            typeExclude: param.typeExclude(),
                            minSize: param.minSize(),
                            actionId: currentAction() ? currentAction().id : "",
                            planId: modelId
                        },
                        page: {
                            curr: 1
                        }
                    };
                    tableIns.reload(searchObjUpdate);
                    return false;
                });

                $("#share-url").click(function (data) {
                    var url = ParamCommon.searchUrlGen(param, "http://" + window.location.host + "/kunlunAssets/index.html#plan/review/param/" + modelId);
                    layer.open({
                        content: shareUrlContent,
                        shadeClose: true,
                        btn: [],
                        title: "请复制",
                        success: function (layero, index) {
                            var inputDom = $(layero.selector).find(".share-url-input");
                            inputDom.val(url);
                            inputDom.select();
                        }
                    });
                    return false;
                });

                $("#share-params-only").click(function () {
                    var paramObj = komapping.toJS(param);
                    delete paramObj.searchDate;
                    delete paramObj.actionId;
                    delete paramObj.curr;
                    delete paramObj.limit;
                    layer.open({
                        content: shareUrlContent,
                        shadeClose: true,
                        btn: [],
                        title: "请复制",
                        success: function (layero, index) {
                            var inputDom = $(layero.selector).find(".share-url-input");
                            inputDom.val(JSON.stringify(paramObj));
                            inputDom.select();
                        }
                    });
                    return false;
                });

                $("#back-to-param").click(function (data) {
                    var url = ParamCommon.searchUrlGen(param, "http://" + window.location.host + "/kunlunAssets/index.html#plan/review/param/" + modelId);
                    router.navigate(url);
                    return false;
                });

                $("#download-link").click(function (data) {
                    var url = ParamCommon.searchUrlGen(param, "http://" + window.location.host + "/back/excel/export/" + modelId);
                    var iframe = $("<iframe style='display: none;'></iframe>");
                    iframe.attr("src", url);
                    $("body").append(iframe);
                    return false;
                });

                $("#download-link-referer").click(function (data) {
                    var url = ParamCommon.searchUrlGen(param, "http://" + window.location.host + "/back/excel/export/referer/" + modelId);
                    var iframe = $("<iframe style='display: none;'></iframe>");
                    iframe.attr("src", url);
                    $("body").append(iframe);
                    return false;
                });
            });
        }
    };
});